<?php


namespace app\admin\controller;


use app\admin\controller\BaseController;
use app\common\model\mysql\Article as ArticleModel;
use app\common\exception\MessageException;
use app\common\validate\ArticleValidate;
use app\common\validate\IDMustBePositiveInt;

class Article extends BaseController
{
    public function list()
    {
        try {
            $params = $this->request->param();
            $result = ArticleModel::list($params);

            return $this->renderSuccess($result);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function create()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new ArticleValidate())->goCheck();
        $params = $this->request->param();
        try {
            $Model = new ArticleModel();

            // 是否草稿 不传 status 默认保存草稿
            $params['status'] = isset($params['status']) ?? 2;

            $result = $Model->create($params);
            if ($result) {
                return $this->renderSuccess(['data' => $result], '添加成功');
            }

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function update()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        return $this->renderSuccess([], '添加成功');
    }

    public function detail()
    {
        (new IDMustBePositiveInt())->goCheck();
        $id = $this->request->param('id');
        try {
            $result = ArticleModel::find($id);
            if ($result) {
                return $this->renderSuccess($result, '添加成功');
            } else {
                return $this->renderFail('文章不存在');
            }
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function delete()
    {
        (new IDMustBePositiveInt())->goCheck();
        $params = $this->request->param();

        try {
            // 删除
            ArticleModel::remove($params);
            return $this->renderSuccess([], '删除成功');

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}